package com.kpx.app.activity;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.cache.FileCache;
import com.kpx.app.configs.Constants;
import com.kpx.app.configs.FileConfig;
import com.kpx.app.configs.SensorControler;
import com.kpx.app.configs.StringUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.CameraPreview;
import com.kpx.app.view.TitleView;

/**
 * 视频录制界面
 *
 * @author CodeApe
 * @version 1.0
 * @Description
 * @update liuyue
 * @date 2013-11-6
 * @updatetime 2014-2-27
 * @Copyright: Copyright (c) 2013 Shenzhen Tentinet Technology Co., Ltd. Inc. All rights reserved.
 */
public class VideoRecodeActivity extends ActivityBase implements OnInfoListener, OnErrorListener {

    /**
     * 开始录制按钮
     */
    private Button btn_Start;
    /**
     * 发送按钮
     */
    private Button btn_Send;
    /**
     * 取消按钮
     */
    private Button btn_Cancel;

    /**
     * 标题栏
     */
    private TitleView view_Title;

    /**
     * 是否正在录制
     */
    private boolean isRecoding = false;
    /**
     * 是否正在预览
     */
    boolean isPreviewing = false;

    /**
     * 录制视频的类
     */
    private MediaRecorder mMediaRecorder;

    /**
     * 录制视屏宽度
     */
    private int video_width = 320;
    /**
     * 录制视屏高度
     */
    private int video_height = 480;

    /**
     * 视屏保存路径
     */
    private String vedioPath = "";
    /**
     * 视频输出质量
     */
    private CamcorderProfile mProfile;
    /**
     * 摄像头对象
     */
    private Camera mCamera;
    /**
     * 摄像头预览对象
     */
    private CameraPreview mPreview;

    /**
     * 记录时间
     */
    private TextView txt_RecordTime;
    /**
     * 记录大小
     */
    private TextView txt_RecordSize;

    /**
     * 定时器
     */
    private final Handler handler = new Handler();
    /**
     * 录制时长
     */
    private int recodeSecond = 20;
    /**
     * 最大录制时长
     */
    private final int maxRecodeSecond = 20;
    /** 录制视屏的大小 */
    // private Size size;
    /**
     * 文本属性获取器
     */
    private SharedPreferences mPreferences;
    /**
     * 视频质量属性键值
     */
    public static final String KEY_VIDEO_QUALITY = "pref_video_quality_key";
    /**
     * 默认视频质量
     */
    public static final String DEFAULT_VIDEO_QUALITY_VALUE = "high";
    /**
     * 高质量视频标准
     */
    private static final String VIDEO_QUALITY_HIGH = "high";
    /**
     * yotube视频质量标准
     */
    private static final String VIDEO_QUALITY_YOUTUBE = "youtube";
    /**
     * 视频流码率
     */
    private static final int VIDEO_BIT_RATE = 256000 * 8;
//    private static final int VIDEO_BIT_RATE = 40 * 1000 * 1000;
    /**
     * 摄像头参数
     */
    private Parameters mParameters;
    /**
     * 视频尺寸比率
     */
    private static final float VIDEO_SIZE_RATE = 1.0f;
    /**
     * 摄像头flash模式key值
     */
    public static final String KEY_VIDEOCAMERA_FLASH_MODE = "pref_camera_video_flashmode_key";
    /**
     * 黑白平衡key值
     */
    public static final String KEY_WHITE_BALANCE = "pref_camera_whitebalance_key";
    /**
     * 色调key值
     */
    public static final String KEY_COLOR_EFFECT = "pref_camera_coloreffect_key";
    private RelativeLayout view_video_screen_frame;
    private SensorControler mSensorControler;

    /**
     * 初始化摄像头参数
     *
     * @version 1.0
     * @createTime 2013-11-24,下午10:46:48
     * @updateTime 2014-2-27
     * @createAuthor CodeApe
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    @SuppressWarnings("deprecation")
    private void initCameraParameters() {
        // 初始化摄像头参数
        // mCamera = getCameraInstance();
        // size = getSupportSize();

        mParameters = mCamera.getParameters();
        mParameters.setRotation(90);
        mParameters.setPreviewSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
        mParameters.setPreviewFrameRate(mProfile.videoFrameRate);
        // Set flash mode.
        String flashMode = mPreferences.getString(KEY_VIDEOCAMERA_FLASH_MODE, getString(R.string.pref_camera_video_flashmode_default));
        List<String> supportedFlash = mParameters.getSupportedFlashModes();
        if (isSupported(flashMode, supportedFlash)) {
            mParameters.setFlashMode(flashMode);
        } else {
            flashMode = mParameters.getFlashMode();
            if (flashMode == null) {
                flashMode = getString(R.string.pref_camera_flashmode_no_flash);
            }
        }

        // Set white balance parameter.
        String whiteBalance = mPreferences.getString(KEY_WHITE_BALANCE, getString(R.string.pref_camera_whitebalance_default));
        if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) {
            mParameters.setWhiteBalance(whiteBalance);
        } else {
            whiteBalance = mParameters.getWhiteBalance();
            if (whiteBalance == null) {
                whiteBalance = Parameters.WHITE_BALANCE_AUTO;
            }
        }

        // Set color effect parameter.
        String colorEffect = mPreferences.getString(KEY_COLOR_EFFECT, getString(R.string.pref_camera_coloreffect_default));
        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
            mParameters.setColorEffect(colorEffect);
        }

        try {
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            e.printStackTrace();
            releaseMediaRecorder();
            recodError();
        }

    }

    /**
     * 初始化大小
     *
     * @version 1.0
     * @createTime 2013-11-7,下午4:30:42
     * @updateTime 2013-11-7,下午4:30:42
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    @SuppressWarnings("deprecation")
    private void initSize() {
        Display display = getWindowManager().getDefaultDisplay();

        // video_width = display.getWidth() * 2 / 3;
        // video_height = 4 * video_width / 3;
        video_width = display.getWidth();
        video_height = display.getHeight();

    }

    /**
     * 获取摄像头实例
     *
     * @return
     * @version 1.0
     * @createTime 2013-11-7,下午3:19:35
     * @updateTime 2013-11-7,下午3:19:35
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private Camera getCameraInstance() {
        Camera camera = null;

        try {
            // 获取Camera实例
            camera = Camera.open();
            camera.setDisplayOrientation(90);
        } catch (Exception e) {
            // 摄像头不可用（正被占用或不存在）
        }
        // 不可用则返回null

        return camera;
    }

    /**
     * 准备mediaRecord
     *
     * @return
     * @version 1.0
     * @createTime 2013-11-7,下午3:31:51
     * @updateTime 2013-11-7,下午3:31:51
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private boolean startRecorder() {
        btn_Cancel.setVisibility(View.GONE);
        btn_Send.setVisibility(View.GONE);
        try {
            // 在这里虽然释放了Camera(camera.unlock();)的使用，但是必须camera.stopPreview();不然录出来的视频有可能花屏
            mCamera.unlock();
            mMediaRecorder = new MediaRecorder();// 创建mediaRecorder对象
            mMediaRecorder.setCamera(mCamera);
            // mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
            // 设置录制视频源为Camera(相机)
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setProfile(mProfile);
            // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
            // mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

            // 设置录制的视频编码h263 h264 三星9300不支持h264编码，坑爹啊
            // String sys = android.os.Build.MODEL;
            // if (sys.contains("GT") && sys.startsWith("GT") ||
            // sys.startsWith("HUAWEI")) {
            // mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
            // } else {
            // mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            // }
            // 音频编码
            // mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mMediaRecorder.setMaxDuration(1000 * 2 * 60);
            // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
            // if (size.width > 0 && size.height > 0)
            // {
            // mMediaRecorder.setVideoSize(size.width, size.height);
            // }

            // 第4步:指定输出文件 ， 设置视频文件输出的路径
            vedioPath = FileConfig.PATH_USER_VIDEO + System.currentTimeMillis() + ".mp4";
            File file = new File(vedioPath);
            mMediaRecorder.setOutputFile(file.getPath());
            mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
            // 设置录像方向
            mMediaRecorder.setOrientationHint(90);

            mMediaRecorder.setOnInfoListener(this);
            mMediaRecorder.setOnErrorListener(this);

            // 第6步:根据以上配置准备MediaRecorder

            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            releaseMediaRecorder();
            recodError();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            releaseMediaRecorder();
            recodError();
            return false;
        } catch (RuntimeException e) {
            ToastUtil.getInstance().showToast(this,"请在设置里面开启录音和录像权限");
            finish();
            e.printStackTrace();
            releaseMediaRecorder();
            recodError();
            return false;
        }

        return true;
    }

    /**
     * 释放mediaRecorder对象
     *
     * @version 1.0
     * @createTime 2013-11-7,下午3:31:06
     * @updateTime 2013-11-7,下午3:31:06
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void releaseMediaRecorder() {
        btn_Cancel.setVisibility(View.VISIBLE);
        btn_Send.setVisibility(View.VISIBLE);
        if (mMediaRecorder != null) {
            // 清除recorder配置
            mMediaRecorder.reset();
            // 释放recorder对象
            mMediaRecorder.release();
            mMediaRecorder = null;
            // 为后续使用锁定摄像头
            if (isPreviewing)
                mCamera.lock();
        }
    }

    /**
     * 录制视频失败
     *
     * @version 1.0
     * @createTime 2013-12-25,下午7:04:42
     * @updateTime 2013-12-25,下午7:04:42
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void recodError() {
        handler.removeCallbacks(recordRunnable);

//		DialogUtil.showSingleMessageDg(this, getString(R.string.dialog_recode_error_title), getString(R.string.warning_recode_video_error), true,
//				new CustomDialog.OnClickListener() {
//
//					@Override
//					public void onClick(CustomDialog dialog, int id, Object object) {
//						dialog.dismiss();
//						finish();
//					}
//				});
    }

    /**
     * 回收摄像头资源
     *
     * @version 1.0
     * @createTime 2013-11-7,下午3:30:33
     * @updateTime 2013-11-7,下午3:30:33
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void releaseCamera() {
        if (mCamera != null) {
            // 为其它应用释放摄像头

            mCamera.release();
            mCamera = null;
        }
    }

    /**
     * 开始录制
     *
     * @version 1.0
     * @createTime 2013-11-7,下午1:10:18
     * @updateTime 2013-11-7,下午1:10:18
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void startRecord() {
        // if (prepareVideoRecorder()) {
        recodeSecond = 20;
        handler.postDelayed(recordRunnable, 1000);

        startRecorder();

        // 通知用户录像已开始
        btn_Start.setText(R.string.activity_video_record_stop);
        isRecoding = true;
    }

    /**
     * 停止录制
     *
     * @version 1.0
     * @createTime 2013-11-7,下午1:26:38
     * @updateTime 2014-2-27 13:10
     * @createAuthor CodeApe
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void stopRecord() {
        if (mMediaRecorder != null) {
            // 停止录像，释放camera
            mMediaRecorder.setOnErrorListener(null);
            mMediaRecorder.setOnInfoListener(null);
            try {
                mMediaRecorder.stop();
            }catch (Exception e){
                ToastUtil.getInstance().showToast(this,"拍摄状态有误，请重试。");
                finish();
                return;
            }
            releaseMediaRecorder();
            if (isPreviewing)
                mCamera.lock();
            // 通知用户录像已停止
            btn_Start.setText(R.string.activity_video_record_start);
            handler.removeCallbacks(recordRunnable);
            isRecoding = false;

        }

    }

    /**
     * 获取手机支持的分辨率
     *
     * @version 1.0
     * @createTime 2013-11-7,下午2:40:21
     * @updateTime 2013-11-7,下午2:40:21
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     *
     */
    /*
     * private Size getSupportSize() { Parameters parameters = mCamera.getParameters(); // 支持的视频录制格式大小 List<Size> supportSizes =
	 * parameters.getSupportedPreviewSizes();
	 * 
	 * Size size = null;// 返回的支持格式 boolean hasSize = false;// 是否存在期望分辨率 int position = 0;// 期望分辨率在列表中的位置 int height = 480;// 期望分辨率的预期高度值（固定值） int
	 * width = 1080;// 期望分辨率的宽度值（待计算）
	 * 
	 * if (supportSizes.size() <= 0) {// 没有支持的视屏格式 return size; } else {// 存在支持的视频格式 for (int i = 0; i < supportSizes.size(); i++) { if
	 * (supportSizes.get(i).height == height) { hasSize = true; if (supportSizes.get(i).width < width) { width = supportSizes.get(i).width; position =
	 * i; } } } }
	 * 
	 * if (!hasSize) {// 不存在分辨率高度为480*xxx的格式 size = supportSizes.get(0); } else {// 存在期望的分辨率 size = supportSizes.get(position); }
	 * 
	 * LogUtil.out("supportSize", "width=" + size.width + ";height=" + size.height); return size;
	 * 
	 * }
	 */

    /**
     * 发送视频
     *
     * @version 1.0
     * @createTime 2013-11-7,下午1:28:01
     * @updateTime 2013-11-7,下午1:28:01
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void send() {

//        Bundle bundle = new Bundle();
//        bundle.putString(getString(R.string.intent_key_vedio), vedioPath);
//        Intent intent = new Intent(this, PlayVideoActivity.class);
//        intent.putExtras(bundle);
//        startActivity(intent);
//        finish();
//        Intent intent = new Intent();
//        intent.putExtra(getString(R.string.intent_key_video), vedioPath);
//        setResult(RESULT_OK, intent);
        FileCache.sharedInstance().put(Constants.KEY_VEDIO_CHCHE,vedioPath);
        finish();

    }

    @Override
    protected void onStop() {
        super.onStop();
        mSensorControler.onStop();
        // 如果正在使用MediaRecorder，首先需要释放它。
        stopRecord();
        // 在暂停事件中立即释放摄像头
        if (mCamera != null) {
            mCamera.lock();
            mCamera.stopPreview();
        }
        releaseCamera();
        isPreviewing = false;
        // 取消屏幕常亮
        stopScreenOn();
    }

    /**
     * 计时线程
     */
    private final Runnable recordRunnable = new Runnable() {

        @Override
        public void run() {
            recodeSecond -= 1;

            DecimalFormat df = new DecimalFormat("00");
            String min = df.format((float) (recodeSecond / 60));
            String sec = df.format((float) recodeSecond % 60);

            txt_RecordSize.setText(StringUtil.formatFileSize(new File(vedioPath).length()));
            txt_RecordTime.setText(min + ":" + sec);

            if (recodeSecond == 0) { // 最大允许录制10秒
                handler.removeCallbacks(recordRunnable);
                stopRecord();
            } else {
                handler.postDelayed(recordRunnable, 1000);
            }
        }
    };

    /**
     * 监听返回按钮
     *
     * @param keyCode
     * @param event
     * @return
     * @version 1.0
     * @createTime 2013-11-8,上午11:41:56
     * @updateTime 2013-11-8,上午11:41:56
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出录制
     *
     * @version 1.0
     * @createTime 2013-11-8,上午11:34:56
     * @updateTime 2013-11-8,上午11:34:56
     * @createAuthor CodeApe
     * @updateAuthor CodeApe
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void exitRecord() {
        if (new File(vedioPath).exists()) {
            new File(vedioPath).delete();
            finish();
//			DialogUtil.showMessageDg(this, "", getString(R.string.warning_recode_video_cancel), new CustomDialog.OnClickListener() {
//
//				@Override
//				public void onClick(CustomDialog dialog, int id, Object object) {
//					new File(vedioPath).delete();
//					dialog.dismiss();
//					finish();
//				}
//			});
        } else {
            finish();
        }
    }

    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {

    }

    @Override
    public void onError(MediaRecorder arg0, int arg1, int arg2) {
        recodError();
    }

    /**
     * 设置摄像头参数
     *
     * @version 1.0
     * @createTime 2014年2月26日 下午5:38:56
     * @updateTime 2014年2月26日 下午5:38:56
     * @createAuthor liuyue
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void readVideoPreferences() {
        String quality = mPreferences.getString(KEY_VIDEO_QUALITY, DEFAULT_VIDEO_QUALITY_VALUE);

        boolean videoQualityHigh = getVideoQuality(quality);

        // Set video quality.
        Intent intent = getIntent();
        if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
            int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            videoQualityHigh = (extraVideoQuality > 0);
        }

        videoQualityHigh = true;
        mProfile = CamcorderProfile.get(videoQualityHigh ? CamcorderProfile.QUALITY_HIGH : CamcorderProfile.QUALITY_LOW);
        if (mProfile == null) {
//			ToastUtil.showToast(VideoRecodeActivity.this, getString(R.string.chat_video_is_wrong));
            finish();
        } else {
            mProfile.videoFrameWidth = (int) (mProfile.videoFrameWidth * VIDEO_SIZE_RATE);
            mProfile.videoFrameHeight = (int) (mProfile.videoFrameHeight * VIDEO_SIZE_RATE);
            mProfile.videoBitRate = VIDEO_BIT_RATE;

            CamcorderProfile highProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mProfile.videoCodec = highProfile.videoCodec;
            mProfile.audioCodec = highProfile.audioCodec;
            mProfile.fileFormat = MediaRecorder.OutputFormat.MPEG_4;
        }
    }

    public static boolean getVideoQuality(String quality) {
        return VIDEO_QUALITY_YOUTUBE.equals(quality) || VIDEO_QUALITY_HIGH.equals(quality);
    }

    private static boolean isSupported(String value, List<String> supported) {
        return supported == null ? false : supported.indexOf(value) >= 0;
    }

    /**
     * 设置预览视图
     *
     * @version 1.0
     * @createTime 2014年2月27日 下午1:11:33
     * @updateTime 2014年2月27日 下午1:11:33
     * @createAuthor liuyue
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void startPreview() {
        if (isPreviewing) {
            return;
        }
        if (mCamera == null) {
            mCamera = getCameraInstance();
        }
        if (mCamera == null) {// 在做一次判断，防止禁止了照相权限
            ToastUtil.getInstance().showToast(VideoRecodeActivity.this,"请开启相机权限");
            finish();
        } else {
            mCamera.lock();
            initCameraParameters();
            // 创建Preview view并将其设为activity中的内容
            mPreview = new CameraPreview(this, mCamera);
            RelativeLayout preview = (RelativeLayout) findViewById(R.id.view_video_screen);
            LayoutParams params = new LayoutParams(video_width, video_height);
            mPreview.setLayoutParams(params);
            preview.addView(mPreview);
            isPreviewing = true;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mSensorControler.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        readVideoPreferences();
        startPreview();
    }

    /**
     * 保持屏幕常亮
     *
     * @version 1.0
     * @createTime 2014年2月27日 下午1:12:16
     * @updateTime 2014年2月27日 下午1:12:16
     * @createAuthor liuyue
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void keepScreenOn() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
     * 取消屏幕常亮
     *
     * @version 1.0
     * @createTime 2014年2月27日 下午1:12:36
     * @updateTime 2014年2月27日 下午1:12:36
     * @createAuthor liuyue
     * @updateAuthor liuyue
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    private void stopScreenOn() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_video_record);
        view_Title = (TitleView) findViewById(R.id.view_title);

        btn_Start = (Button) this.findViewById(R.id.btn_start);
        btn_Send = (Button) this.findViewById(R.id.btn_send);
        btn_Cancel = (Button) this.findViewById(R.id.btn_cancel);
        view_video_screen_frame = (RelativeLayout) this.findViewById(R.id.view_video_screen_frame);

        txt_RecordSize = (TextView) findViewById(R.id.txt_record_size);
        txt_RecordTime = (TextView) findViewById(R.id.txt_record_time);
        txt_RecordTime.setText("可录制视频时长为20秒");
        initSize();

        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        readVideoPreferences();
        startPreview();
        mSensorControler = SensorControler.getInstance();

        mSensorControler.setCameraFocusListener(new SensorControler.CameraFocusListener() {
            @Override
            public void onFocus() {
                mCamera.autoFocus(new Camera.AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean success, Camera camera) {
                        if (success) {
                            camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
                        }
                    }

                });
            }
        });
    }

    @Override
    public void initData() {
// 按钮监听
        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_start:

                        if (isRecoding) {// 如果正在录制，停止录制
                            stopRecord();
                        } else {// 开始录制
                            if (new File(vedioPath).exists()) {
                                // 如果文件已经存在
                                startRecord();
                                keepScreenOn();
//							DialogUtil.showMessageDg(VideoRecodeActivity.this, "", getString(R.string.warning_recode_video_cover),
//									new CustomDialog.OnClickListener() {
//
//										@Override
//										public void onClick(CustomDialog dialog, int id, Object object) {
//											new File(vedioPath).delete();
//											startRecord();
//											keepScreenOn();
//											dialog.dismiss();
//										}
//									});
                            } else {
                                startRecord();
                                keepScreenOn();
                            }
                        }
                        break;
                    case R.id.btn_cancel:
                        exitRecord();
                        break;

                    case R.id.btn_send:
                        send();
                        break;
                    case R.id.view_video_screen_frame:
                        mCamera.autoFocus(new Camera.AutoFocusCallback() {
                            @Override
                            public void onAutoFocus(boolean success, Camera camera) {
                                if (success) {
                                    camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
                                }
                            }

                        });
                        break;

                    default:
                        break;
                }
            }
        };

        btn_Start.setOnClickListener(listener);
        btn_Send.setOnClickListener(listener);
        btn_Cancel.setOnClickListener(listener);
        view_video_screen_frame.setOnClickListener(listener);

        // 返回按钮
        view_Title.setBackClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                exitRecord();
            }
        });
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

}
